﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Reflection;

namespace SkyDriveSimpleViewer
{
	/// <summary>
	/// Window of application.
	/// </summary>
	public partial class MainWindow : Window
	{
		private SkyDriveConnection _SkyDrive;

		public MainWindow()
		{
			InitializeComponent();
			_SkyDrive = null;

			System.IO.Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("SkyDriveSimpleViewer.Properties.SkyDrive.png");
			BitmapDecoder i = BitmapDecoder.Create(s, BitmapCreateOptions.None, BitmapCacheOption.Default);
			s.Close();
			Icon = i.Frames[0];
		}

		private void OnWindowLoaded(object sender, RoutedEventArgs e)
		{
			UserName.Focus();
		}

		private void ShowMessage(string msg)
		{
			Message.Style = (Style)FindResource("Header");
			Message.Content = msg;
		}

		private void ShowError(string msg)
		{
			Message.Style = (Style)FindResource("HeaderWhenError");
			Message.Content = msg;
		}

		private void OnLoginButton(object sender, RoutedEventArgs e)
		{
			FolderList.Visibility = Visibility.Hidden;
			WebDAVUrlPanel.Visibility = Visibility.Hidden;
			ItemList.Visibility = Visibility.Hidden;

			_SkyDrive = new SkyDriveConnection(UserName.Text, Password.Password);
			ShowMessage("Trying to login and fetch folders. Please wait...");
			ThreadPool.QueueUserWorkItem(state => DoLogin());
		}

		private void DoLogin()
		{
			string errorMsg = null;
			try
			{
				SkyDriveFolder[] folders = _SkyDrive.GetDavFolders();
				Dispatcher.Invoke(new Action<SkyDriveFolder[]>(AfterLogin), 
					System.Windows.Threading.DispatcherPriority.Normal, new object[] { folders });
			}
			catch (PassportException err)
			{
				if (err.Why == PassportException.Reason.Authentication)
					errorMsg = "Wrong user name or password";
				else
					errorMsg = err.Message;
			}
			catch (Exception err)
			{
				errorMsg = "An error occured: " + err.Message;
			}
			if (errorMsg != null)
			{
				Dispatcher.Invoke(new Action<string>(ShowError), System.Windows.Threading.DispatcherPriority.Normal, errorMsg);
			}
		}

		private void AfterLogin(SkyDriveFolder[] folders)
		{
			FolderList.Visibility = Visibility.Visible;
			FolderList.ItemsSource = folders;
			ShowMessage(string.Format("You have {0} folders in SkyDrive", folders.Length));
		}

		private void OnFolderSelected(object sender, SelectionChangedEventArgs e)
		{
			if (FolderList.SelectedIndex < 0)
				return;

			SkyDriveFolder folder = (SkyDriveFolder)FolderList.SelectedItem;
			WebDAVUrlPanel.Visibility = Visibility.Visible;
			WebDAVUrl.Text = folder.WebDAVUrl;
			ItemList.Visibility = Visibility.Hidden;
			ShowMessage("Fetch contents of folder. Please wait...");
			ThreadPool.QueueUserWorkItem(state => DoFolderSelected((SkyDriveFolder)state), folder);
		}

		private void DoFolderSelected(SkyDriveFolder folder)
		{
			string errorMsg = null;
			try
			{
				SkyDriveItem[] items = _SkyDrive.GetDavFolderContent(folder);
				Dispatcher.Invoke(new Action<SkyDriveFolder, SkyDriveItem[]>(AfterFolderSelected),
					System.Windows.Threading.DispatcherPriority.Normal, new object[] { folder, items });
			}
			catch (Exception err)
			{
				errorMsg = err.Message;
			}
			if (errorMsg != null)
			{
				Dispatcher.Invoke(new Action<string>(ShowError), System.Windows.Threading.DispatcherPriority.Normal, errorMsg);
			}
		}

		private void AfterFolderSelected(SkyDriveFolder folder, SkyDriveItem[] items)
		{
			ItemList.Visibility = Visibility.Visible;
			ItemList.ItemsSource = items;
			ShowMessage(string.Format("This folder has {0} items in it", items.Length));
		}
	}
}
